package com.dongdong.bookstore.security.components;

import cn.hutool.json.JSONUtil;
import com.dongdong.bookstore.common.api.ResultData;
import com.dongdong.bookstore.common.api.ReturnCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现无权访问的Handler
 * @author chiangkai
 * @date 2021-09-17
 * @email chiangkk@163.com
 */
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(ResultData.fail(ReturnCode.ACCESS_DENIED.getCode(),ReturnCode.ACCESS_DENIED.getMessage())));
        response.getWriter().flush();
    }
}
